var httpFileTypes=require("./HttpFileTypes.js");
var SystemEvent=require("../event/SystemEvent")
var http = require('http');
var https=require("https");
var url=require('url');
var fs=require('fs');
var path=require('path');
var logManager=require("../Logs")

var HttpServer=Class.extend({
    _port:0,
    _server:null,
    _types:httpFileTypes,
    _eventManager:null,
    ctor:function(port,keyData,eventManager){
        this.eventManager=eventManager;
        this._port=port;
        if(keyData) {
            logManager.logM("https server init,port="+port);
            var options = {
                key: fs.readFileSync(keyData.key,"utf8"),
                cert: fs.readFileSync(keyData.cert,"utf8")
            }
            if(keyData.ca){
                options.ca=fs.readFileSync(keyData.cert,"utf8");
            }
            this._server = https.createServer(options,this.onRequest.bind(this));
        }else {
            logManager.logM("http server init,port="+port);
            this._server = http.createServer(this.onRequest.bind(this));
        }
        this._server.listen(this._port);
    },
    onRequest:function(request, response) {
        var self=this;
        var pathname = url.parse(request.url).pathname;
        var realPath = path.join("www", pathname);
        realPath=decodeURI(realPath);
        request._temBody="";
        request._chunk=[];
        request.on('data', function (chunk) { //解析body   https://www.jianshu.com/p/53588cda1f50
            if(!request._chunk)request._chunk=[]
            request._chunk.push(chunk);
            // request._temBody += chunk;
            self.eventManager.dispatchEvent(SystemEvent.HTTP_REQUEST_DATA,[self._port,pathname,request,response])
        });
        request.on('end', function () {
            request.body=request._chunk?request._chunk.join(""):""//request._temBody;
            var result=self.eventManager.dispatchEvent(SystemEvent.HTTP_REQUEST_END,[self._port,pathname,request,response])
            if(!result)
                fs.exists(realPath, self.onFileExist.bind(self,response,realPath));
        });
        self.eventManager.dispatchEvent(SystemEvent.HTTP_REQUEST_BEGIN,[self._port,pathname,request,response]);
    },
    onFileExist:function (response,realPath,exists) {
        if (!exists) {
            if(!response.finished) {
                response.setHeader("Access-Control-Allow-Origin", "*");
                response.setHeader("Access-Control-Allow-Headers", "token,content-type");
                response.writeHead(404, {'Content-Type': 'text/plain'});
                response.write("This request URL " + " was not found on this server.");
                response.end();
            }
        } else {
            fs.readFile(realPath, "binary", this.onFileReadOver.bind(this,response,realPath));
        }
    },
    onFileReadOver:function (response,realPath,err, file) {
        var ext = path.extname(realPath);
        ext = ext ? ext.slice(1) : 'unknown';
        if (err) {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Headers", "token,content-type");
            response.writeHead(500, {'Content-Type': 'text/plain'});
            response.end(err.toString());
        } else {
            var contentType = this._types[ext] || "text/plain";
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Headers", "token,content-type");
            response.writeHead(200, {'Content-Type': contentType});
            response.write(file, "binary");
            response.end();
        }
    },
    destruct:function(){
        if(this._server) {
            this._server.stop();
            this._server=null;
        }
    }
});
module.exports=HttpServer;